<?php
namespace Beerus\Modules\BlackCard\Controllers;

use Doraemon\model\BlackCard\BlackTips;
use Doraemon\tools\LinkFormat;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Doraemon\model\DecorationTask\Tips;


class TipsController extends Controller
{

    const PAGE_SIZE = 20;

    //任务列表
    public function index(Request $request,Content $content){
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page');

        $limit = [
            ($page - 1) * $perPage, $perPage
        ];

        $selector_params = $request->input("_selector");
        if ($selector_params && $selector_params['show_type'] != 0){
            $show_type = $selector_params['show_type'];
        } else {
            $show_type = array_keys(BlackTips::SHOW_TYPE_NAME_MAP);
        }

        $result = [];
        $result['list'] = BlackTips::getTipList($limit, $show_type);
        $result['total'] = BlackTips::getCount();
        $grid = new pGridDataModel($result['list'], $result['total'], [
            'per_page' => $perPage
        ]);

        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();

                $grid->column('id');
                $grid->column("show_type", '展示位置')->display(function () {
                    return BlackTips::SHOW_TYPE_NAME_MAP[$this->show_type];
                });
                $grid->column('title', '提示信息')->width(250);
                $grid->column('link', '链接地址')->linkSelect(false);
                $grid->column('addtime', '添加时间');
                $grid->column('edittime', '修改时间');
                $grid->column('admin_id', '操作人')->display(function(){
                    if(!$this->admin_id) {
                        return '暂无';
                    }else{
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->selector(function (Grid\Tools\Selector $selector) {
                    $selector->selectOne('show_type', '展示位置', array_merge([0 => "全部"], BlackTips::SHOW_TYPE_NAME_MAP));
                });
            });

        $content->row($gridList);
        return $content
            ->header('黑卡广播语')
            ->description(' ')
            ->breadcrumb(['text' => 'user']);
    }


    //提示信息添加页面
    public function edit(Request $request,Content $content, $id = 0)
    {
        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('')
                ->breadcrumb(
                    ['text' => '黑卡广播', 'url' => '/blackCard/tips/index'],
                    ['text' => '添加广播信息', 'url' => '/blackCard/tips/index/create']
                )
                ->body(self::editAction($request, $id , True));
        } else {
            return $content
                ->header('黑卡广播列表')
                ->breadcrumb(
                    ['text' => '黑卡广播', 'url' => '/blackCard/tips/index'],
                    ['text' => '修改广播信息', 'url' => '/blackCard/tips/index/'.'/'.$id.'/edit']
                )
                ->body(self::editAction($request, $id, False));
        }

    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            $data = BlackTips::getTipsById($id);
            $data['link'] = [
                'link_type' => $data['link_type'],
                'link_params' => $data['link_params'],
            ];
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }

        $form->text('title', '广播信息')->required('不能为空');
        $form->linkSelect('link', '跳转链接');
        $form->select('show_type', '展示位置')->options(BlackTips::SHOW_TYPE_NAME_MAP)->required('不能为空');
        $form->action('/admin/blackCard/tips/index/save');
        return $form->render();
    }

    //添加、修改提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        if(isset($request['id'])) {
            $data = [
                'title' => $request['title'],
                'link_type' => $request['link_type'],
                'show_type' => $request['show_type'],
                'link_params' => json_encode($request['link_params'], JSON_UNESCAPED_UNICODE),
                'link' => LinkFormat::generateSingleLink($request['link_type'], $request['link_params']),
                'tips_status' => 1,
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id,
            ];

            $rs = BlackTips::edit($data, $request['id']);
            if($rs) {
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
                return redirect('/admin/blackCard/tips/index')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '修改失败'
                ]);
                return redirect('/admin/blackCard/tips/index')->with(compact('error'));
            }
        } else {
            $data = [
                'title' => $request['title'],
                'link_type' => $request['link_type'],
                'show_type' => $request['show_type'],
                'link_params' => json_encode($request['link_params'], JSON_UNESCAPED_UNICODE),
                'link' => LinkFormat::generateSingleLink($request['link_type'], $request['link_params']),
                'tips_status' => 1,
                'addtime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];
            $rs = BlackTips::add($data);
            if($rs) {
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
                return redirect('/admin/blackCard/tips/index')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '添加失败'
                ]);
                return redirect('/admin/blackCard/tips/index')->with(compact('error'));
            }
        }

    }

    //删除
    public function del($id = 0)
    {
        $tips_info = BlackTips::getTipsById($id);
        if($tips_info) {
            $data = [
                'tips_status' => Tips::STATUS_DELETE,
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];

            $rs = BlackTips::edit($data, $id);
            if($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        }

    }

}